package com.itheima.wisdomnext.controller;

import com.itheima.wisdomnext.entity.Comment;
import com.itheima.wisdomnext.entity.CommentShow;
import com.itheima.wisdomnext.entity.Result.ResponseResult;
import com.itheima.wisdomnext.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin // 允许跨域请求
@RestController
@RequestMapping("/api/comment") // 路由前缀
public class CommentController {

    @Autowired
    private CommentService commentService;

    /**
     * 根据帖子 ID 获取所有评论
     *
     * @param postId 帖子 ID
     * @param userId 可选参数，用户 ID，用于判断当前用户是否点赞了某评论
     * @return 当前帖子的评论列表（包含用户信息、点赞状态、回复数量）
     */
    @GetMapping("/post/{postId}")
    public ResponseResult<List<CommentShow>> getCommentsByPostId(@PathVariable Integer postId,
                                                                 @RequestParam(required = false) Integer userId) {
        List<CommentShow> commentShows = commentService.getCommentsByPostIdWithDetails(postId, userId);
        return ResponseResult.success("查询成功", commentShows);
    }

    /**
     * 获取指定评论及其所有回复
     *
     * @param commentId 评论 ID
     * @param userId 可选参数，用户 ID，用于判断是否点赞及获取回复详情
     * @return 评论及其所有回复详情
     */
    @GetMapping("/reply/{commentId}")
    public ResponseResult<CommentShow> getCommentWithReplies(@PathVariable Integer commentId,
                                                             @RequestParam(required = false) Integer userId) {
        CommentShow commentShow = commentService.getCommentWithReplies(commentId, userId);
        if (commentShow == null) {
            return ResponseResult.success("评论不存在", null);
        }
        return ResponseResult.success("查询成功", commentShow);
    }

    /**
     * 添加一条评论
     *
     * @param comment 评论实体
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseResult<Object> addComment(@RequestBody Comment comment) throws Exception{
        commentService.addComment(comment);
        return ResponseResult.success("评论添加成功", null);
    }

    /**
     * 更新评论内容
     *
     * @param comment 评论实体
     * @return 更新后的评论信息
     */
    @PutMapping("/update")
    public ResponseResult<Comment> updateComment(@RequestBody Comment comment) throws Exception{
        Comment updatedComment = commentService.updateComment(comment);
        return ResponseResult.success("评论更新成功", updatedComment);
    }

    /**
     * 删除评论
     *
     * @param id 评论 ID
     * @return 删除操作结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseResult<Object> deleteComment(@PathVariable Integer id) throws Exception{
        commentService.deleteComment(id);
        return ResponseResult.success("评论删除成功", null);
    }
}
